/**   
*
* @创建人：Liuyong   
* @创建时间：2013-11-4 下午05:13:41   
*    
*/ 
package com.crmsys.common.interceptor;

/**   
 *
 * @描述：   
 * @创建人：Liuyong   
 * @创建时间：2013-11-4 下午05:13:41   
 * @修改人：Liuyong   
 * @修改时间：2013-11-4 下午05:13:41   
 * @修改备注：   
 * @version 1.0
 *    
 */

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.crmsys.auth_framework.auth.model.CUser;
import com.crmsys.common.constant.AuthConstants;
import com.crmsys.common.util.SessionUtil;


public class LoginInterceptor implements HandlerInterceptor {
  
  /**
   * 不过滤URL
   */
  private String[] excludeUrl;
  
  /**
   * 重新认证URL
   */
  private String   returnPage;
  
  public String[] getExcludeUrl() {
    return excludeUrl;
  }


  public void setExcludeUrl(String[] excludeUrl) {
    this.excludeUrl = excludeUrl;
  }


  public String getReturnPage() {
    return returnPage;
  }


  public void setReturnPage(String returnPage) {
    this.returnPage = returnPage;
  }


  public LoginInterceptor(){  
    }
  
 
  
  public void afterCompletion(HttpServletRequest arg0,
      HttpServletResponse arg1, Object arg2, Exception arg3)
      throws Exception {
    
    
  }

  
  public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
      Object arg2, ModelAndView arg3) throws Exception {
    
    
  }


  
  public boolean preHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler) throws Exception {
    String url = request.getRequestURI();
    //排除不拦截URI
    if(excludeURL(url)){
      return true;
    }
    if(SessionUtil.getLoginUserInfo(request)==null){
    	//如果当前Session没有用户信息，代表没有登陆,就返回登陆框重新登陆
    	boolean isAjaxRequest = isAjaxRequest(request);  
    	if (isAjaxRequest) {
    		response.setCharacterEncoding("UTF-8");  
    		response.sendError(HttpStatus.UNAUTHORIZED.value(),  "您已经太长时间没有操作,请刷新页面");  
    	}  
    	request.getRequestDispatcher("index").forward(request,response);//跳转到登陆页
    	return false;
    }else{
    	return true;
    }
          
  }
  
  @SuppressWarnings("unchecked")
  private String gennerRedirectUrl(HttpServletRequest request,
      HttpServletResponse response){
    Map map = request.getParameterMap();// 获取parameterMap来进行遍历
    // 用getParameterNames()也可以
    Set keySet = map.keySet();// 取出keySet
    
    StringBuffer url =new StringBuffer();
    url.append(request.getRequestURI());
    if (!((request.getRequestURI()!=null) && (request.getRequestURI().indexOf('?')>-1))){
      url.append("?");// 构建重定向的url
    }
    for (Iterator it = keySet.iterator(); it.hasNext();) {
      String name = it.next().toString();
      String value = request.getParameter(name) == null ? "" : request
          .getParameter(name).toString();
      url.append(name).append("=").append(value).append("&");
    }
    return url.toString();
  }
  
  
  //排除URL
  private boolean excludeURL(String url) {
    boolean flag=false;
    url=url.toLowerCase();
      for (String str : excludeUrl) {
        if (url.indexOf(str.toLowerCase())>0) {
          flag = true;
          break;
        }
      }
    return flag;
  }
  /** 
   * 判断是否为Ajax请求 
   * 
   * @param request HttpServletRequest 
   * @return 是true, 否false 
   */  
  public static boolean isAjaxRequest(HttpServletRequest request) {  
   return request.getRequestURI().startsWith("/api");  

  } 

}

